package com.open.web.exception;

import com.open.basic.BaseResponse;
import com.open.basic.constant.BizConstant;
import com.open.basic.exception.BizException;
import com.open.basic.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author: codex
 * @Date: 2024/4/21 11:54
 * @Version: V1.0
 * @description: desc:全局异常处理器
 */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : allErrors) {
            errorMsg.append(error.getDefaultMessage()).append("; ");
        }
        String str = String.format("e===MethodArgumentNotValidException: %s", e.getMessage());
        log.error(str, e);
        return BaseResponse.fail(BizConstant.DATA_INVALID.getCode(), errorMsg.toString());
    }

    @ExceptionHandler(BizException.class)
    public BaseResponse<String> handleException(BizException e) {
        String str = String.format("e===BizException: %s", e.getMessage());
        log.error(str, e);
        return BaseResponse.fail(BizConstant.BIZ_EXCEPTION.getCode(), e.getMessage());
    }

    @ExceptionHandler(SystemException.class)
    public BaseResponse<String> handleException(SystemException e) {
        String str = String.format("e===SystemException: %s", e.getMessage());
        log.error(str, e);
        return BaseResponse.fail(BizConstant.SYSTEM_EXCEPTION.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<String> handleException(RuntimeException e) {
        String str = String.format("e===handleException: %s", e.getMessage());
        log.error(str, e);
        return BaseResponse.fail(BizConstant.SYSTEM_EXCEPTION.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse<String> handleException(Exception e) {
        String str = String.format("e===Exception: %s", e.getMessage());
        log.error(str, e);
        return BaseResponse.fail(BizConstant.SYSTEM_EXCEPTION.getCode(), e.getMessage());
    }
}
